<template>
  <el-card class="forget-container" shadow="never">
    <div class="tc fs-20 fw-b" slot="header">重置密码</div>
    <el-steps :active="active" finish-status="success" simple>
      <el-step title="验证身份"></el-step>
      <el-step title="设置密码"></el-step>
    </el-steps>
    <el-form
      ref="forgetForm"
      :model="forgetForm"
      :rules="forgetRules"
      class="mt-30"
      auto-complete="on"
      label-width="80px"
    >
      <template v-if="active==0">
        <el-form-item prop="mobile" label="手机号">
          <el-input v-model="forgetForm.mobile" placeholder="请输入手机号" type="text"></el-input>
        </el-form-item>
        <el-form-item prop="valideCode" label="验证码">
          <el-input placeholder="请输入验证码" v-model="forgetForm.valideCode">
            <template slot="append">
              <span v-show="show" @click="send" class="pointer">验证码</span>
              <span v-show="!show" class="count pointer">{{count}} s</span>
            </template>
          </el-input>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item prop="account" label="当前企业" v-if="company.length>1">
          <el-select v-model="forgetForm.account" placeholder="请选择" class="full-w">
            <el-option
              v-for="item in company"
              :key="item.account"
              :label="item.corpName"
              :value="item.account"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input
            ref="password"
            v-model="forgetForm.newPassword"
            :type="passwordType"
            placeholder="密码必须包含字母和数字,且在6~18位之间"
          >
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              slot="suffix"
              @click="showPwd"
            />
          </el-input>
        </el-form-item>
      </template>
      <div class="tc">
        <el-button
          :loading="loading"
          type="primary"
          style="width:80%;margin-top:30px"
          @click="next('forgetForm')"
        >{{active==0?"下一步":"完成"}}</el-button>
      </div>
    </el-form>
  </el-card>
</template>

<script>
import { validPhone, validPswd } from "@/utils/validate";
import {
  getMobileValideCode,
  getCorpAccountByMobile,
  setPasswordByMobileValideCode
} from "api/user";
import md5 from "js-md5";
const TIME_COUNT = 60; //更改倒计时时间
export default {
  data() {
    const validateMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号"));
      }
      setTimeout(() => {
        if (!validPhone(value)) {
          callback(new Error("手机号不正确"));
        } else {
          callback();
        }
      }, 300);
    };
    const validatePswd = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入新密码"));
      }
      setTimeout(() => {
        if (!validPswd(value)) {
          return callback(new Error("密码必须包含字母和数字,且在6~18位之间"));
        }
        callback();
      }, 300);
    };
    return {
      forgetForm: {
        mobile: "",
        valideCode: "",
        account: "",
        newPassword: ""
      },
      forgetRules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ],
        valideCode: [
          { required: true, message: "请输入验证码", trigger: "blur" }
        ],
        account: [
          {
            required: true,
            message: "请选择需要修改密码的企业",
            trigger: "change"
          }
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { validator: validatePswd, trigger: "blur" }
        ]
      },
      show: true, // 初始启用按钮
      count: "", // 初始化次数
      timer: null,
      loading: false,
      company: [],
      active: 0,
      passwordType: "password",
      copyData: {}
    };
  },
  methods: {
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    next(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.active == 0) {
            //验证身份
            this.getCompanys().then(res => {
              this.loading = false;
              this.active++;
            });
          } else {
            this.submit();
          }
        } else {
          console.log("submit error");
        }
      });
    },
    // 获取验证码
    send() {
      this.$refs.forgetForm.validateField("mobile", phoneError => {
        if (!phoneError) {
          getMobileValideCode({ mobile: this.forgetForm.mobile })
            .then(() => {
              this.countDown();
              this.$confirm("验证码已发送至登记手机号上，请查收。", {
                confirmButtonText: "确定",
                center: true
              });
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        }
      });
    },
    // 倒计时
    countDown() {
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer); // 清除定时器
            this.timer = null;
          }
        }, 1000);
      }
    },
    getCompanys() {
      return new Promise((resolve, reject) => {
        if (this.loading) return;
        this.loading = true;
        let data = {
          mobile: this.forgetForm.mobile,
          valideCode: this.forgetForm.valideCode
        };
        getCorpAccountByMobile(data)
          .then(res => {
            let result = res.data;
            if (!result) return;
            if (result.length == 0) {
              this.$confirm("暂无所属企业，请联系企业添加账号！", "温馨提示", {
                confirmButtonText: "确定",
                center: true
              });
              reject();
            } else {
              if (result.length == 1) {
                this.forgetForm.account = result[0].account;
              }
              if (result.length > 1) {
                // 多个企业需要选择登录
                this.company = result;
              }
              this.copyData = data;
              resolve();
            }
            this.loading = false;
          })
          .catch(err => {
            this.loading = false;
            this.$message.error(err.msg);
          });
      });
    },
    submit() {
      if (this.loading) return;
      this.loading = true;
      let forgetForm = this.forgetForm;
      forgetForm.newPassword = md5(forgetForm.newPassword);
      let data = Object.assign(this.copyData, forgetForm);
      setPasswordByMobileValideCode(data)
        .then(res => {
          this.$alert("当前账号 "+forgetForm.account+" 密码重置成功！", "温馨提示", {
            confirmButtonText: "去登陆",
            center: true,
            callback: action => {
              history.go(-1);
            }
          });
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    }
  }
};
</script>

<style lang='scss' scoped>
.full-w {
  width: 100%;
}
.forget-container {
  width: 520px;
  position: relative;
  left: 50%;
  top: 160px;
  transform: translateX(-50%);
  overflow: hidden;
}
</style>
